package de.esk.fraunhofer.activity.LadeVorgaenge;

import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;
import de.esk.fraunhofer.ECar;
import de.esk.fraunhofer.Einstellungen;
import de.esk.fraunhofer.MegTyp;
import de.esk.fraunhofer.R;
import de.esk.fraunhofer.ECM_DatenbankOperation.Query.Query_LadevorgaengeConfig;
import de.esk.fraunhofer.ECM_DatenbankOperation.Update.LVConfigUpdate;
import de.esk.fraunhofer.XMLAnalyser.XML_LadevorgaengerConfigItem;
import de.esk.fraunhofer.bluetoothlayer.BlueToothClient;
import de.esk.fraunhofer.bluetoothlayer.DeviceListActivity;

public class LadeVorgaengeConfig extends PreferenceActivity implements MegTyp{
	//**********************************************************************************************
	//debug
    public static final boolean D=Einstellungen.Debug;
    private static final String TAG = "Ladevorgaenge_config";    
    public static final boolean iD=Einstellungen.iDebug;
    
    //Intent request codes
    private static final int REQUEST_CONNECT_DEVICE = 1;  
    private static final int REQUEST_ENABLE_BT = 2;

    //Layout Views
    private TextView mTitle;
    private CheckBoxPreference Intelligent_AC_dch_enable;
    private CheckBoxPreference Intelligent_AC_enable_ext_control;
    private CheckBoxPreference Intelligent_AC_enable_control_table;
    private CheckBoxPreference DC_dch_enable;
    private CheckBoxPreference DC_enable_ext_control;
    private CheckBoxPreference DC_enable_control_table;
    private EditTextPreference SoC_limit_dch_min;
    private EditTextPreference tarif_ID;
    private EditTextPreference minimal_dch_energy_price;
    private EditTextPreference Simple_AC_P_ch_max;
    private EditTextPreference Battery_Modus;
    private ProgressDialog p_dialog;
    
    //Name of the connected device
    private String mConnectedDeviceName = null;
	
	//Handler
	private final Handler _Handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
        	switch(msg.what){
        	case MESSAGE_XMLOBJ: 
        		if(msg.obj instanceof XML_LadevorgaengerConfigItem){//filter
        			if(D) Log.e(TAG, "LadevorgaengeConfig received xml object.");
					//************load data from incoming xml item********************
	        		XML_LadevorgaengerConfigItem xmlLVC=(XML_LadevorgaengerConfigItem)msg.obj;
	        		
					//***********set GUI***************************
	        		Intelligent_AC_dch_enable.setChecked(xmlLVC.intelligent_AC_dch_enable);
	        		Intelligent_AC_enable_ext_control.setChecked(xmlLVC.intelligent_AC_enable_ext_control);
	        		Intelligent_AC_enable_control_table.setChecked(xmlLVC.intelligent_AC_enable_control_table);
	        		DC_dch_enable.setChecked(xmlLVC.DC_dch_enable);
	        		DC_enable_ext_control.setChecked(xmlLVC.DC_enable_ext_control);
	        		DC_enable_control_table.setChecked(xmlLVC.DC_enable_control_table);
	        		SoC_limit_dch_min.setText(String.valueOf(xmlLVC.SoC_limit_dch_min));
	        		tarif_ID.setText(String.valueOf(xmlLVC.tarif_ID));
	        		minimal_dch_energy_price.setText(String.valueOf(xmlLVC.minimal_dch_energy_price));
	        		Simple_AC_P_ch_max.setText(String.valueOf(xmlLVC.Simple_AC_P_ch_max));
	        		Battery_Modus.setText(String.valueOf(xmlLVC.battery_modus));
	        		p_dialog.dismiss();
	        	}
        		break;
            case MESSAGE_STATE_CHANGE:
                if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
                switch (msg.arg1) {
                case BlueToothClient.STATE_CONNECTED:                
                    mTitle.setText(R.string.title_connected_to);
                    mTitle.append(mConnectedDeviceName);
                    break;
                case BlueToothClient.STATE_CONNECTING:
                    mTitle.setText(R.string.title_connecting);
                    break;
                case BlueToothClient.STATE_NONE:
                    mTitle.setText(R.string.title_not_connected);
                    break;
                }
                break;	                
            case MESSAGE_DEVICE_NAME:
                // save the connected device's name
                mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
                Toast.makeText(getApplicationContext(), "Connected to "
                               + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
                break;
            case MESSAGE_TOAST:
                Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
                               Toast.LENGTH_SHORT).show();
                break;
        	}
        }		
	};
	//************************************Activity life cycle*********************************************
	@Override
	public void onCreate(Bundle savedInstanceState){
    	if(D) Log.e(TAG,"+++ On Created +++");
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
    	super.onCreate(savedInstanceState); 
    	// Set up the window layout
        addPreferencesFromResource(R.xml.ladevorgaengeconfig);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
        
        Intelligent_AC_dch_enable=(CheckBoxPreference) findPreference("intelligent_ac_dch_enable");
        Intelligent_AC_enable_ext_control=(CheckBoxPreference) findPreference("intelligent_ac_enable_ext_control");
        Intelligent_AC_enable_control_table=(CheckBoxPreference) findPreference("intelligent_ac_enable_control_table");
        DC_dch_enable=(CheckBoxPreference) findPreference("dc_dch_enable");
        DC_enable_ext_control=(CheckBoxPreference) findPreference("dc_enable_ext_control");
        DC_enable_control_table=(CheckBoxPreference) findPreference("dc_enable_control_table");
        SoC_limit_dch_min=(EditTextPreference) findPreference("soc_limit_dch_min");
        tarif_ID=(EditTextPreference) findPreference("tarif_id");
        minimal_dch_energy_price=(EditTextPreference) findPreference("minimal_dch_energy_price");
        Simple_AC_P_ch_max=(EditTextPreference) findPreference("simple_ac_p_ch_max");
        Battery_Modus=(EditTextPreference) findPreference("battery_modus");
        
        // Set up the custom title
        mTitle = (TextView) findViewById(R.id.title_left_text);
        mTitle.setText(R.string.app_name);
        mTitle = (TextView) findViewById(R.id.title_right_text);
        //send Query;
        sendtoECM(Query_LadevorgaengeConfig.xml_query_LCQ);
    }
	
	@Override
	public void onStart(){
		super.onStart();

        if(D) Log.e(TAG, "++ ON START ++");

        // If BT is not on, request that it be enabled.
        if (!ECar.mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        } else {
            if(ECar.mBluetoothClient==null) setupBlueToothClient();
        }		

		p_dialog = ProgressDialog.show(this, "", 
	            "Loading. Please wait...", true);
	}
	
	@Override
	public void onResume(){
		super.onResume();
		if(D) Log.e(TAG, "+ ON RESUME +");    
		mTitle.setText(ECar.ConnectionStatus);	
		//mHandler should be caugth here for infoswitch
		ECar.mBluetoothClient.setmHandler(_Handler);
	}
	
	@Override
	public void onPause(){
        super.onPause();
        if(D) Log.e(TAG, "- ON PAUSE -");        
        //save ConncetionStatus
        ECar.ConnectionStatus=mTitle.getText();
	}
	
    @Override
    public void onStop() {
        super.onStop();
        if(D) Log.e(TAG, "-- ON STOP --");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        sendConfig(this);
        if(D) Log.e(TAG, "--- ON DESTROY ---");
    }
    //***********************************************************************************************
    /**
     * Retrieve all the value from the preference component and sent them to ECM.
     */
    private void sendConfig(LadeVorgaengeConfig ladeVorgaengeConfig) {
      SharedPreferences s=PreferenceManager.getDefaultSharedPreferences(this);
      XML_LadevorgaengerConfigItem xml_lci=new XML_LadevorgaengerConfigItem(
			s.getBoolean("intelligent_ac_dch_enable", false),
			s.getBoolean("intelligent_ac_enable_ext_control",false),
			s.getBoolean("intelligent_ac_enable_control_table",false),
			s.getBoolean("dc_dch_enable",false),
			s.getBoolean("dc_enable_ext_control",false),
			s.getBoolean("dc_enable_control_table",false),
			Integer.valueOf(s.getString("soc_limit_dch_min","-1")),
			Integer.valueOf(s.getString("tarif_id","-1")),
			Integer.valueOf(s.getString("minimal_dch_energy_price","-1")),
			Integer.valueOf(s.getString("simple_ac_p_ch_max","-1")),
			Integer.valueOf(s.getString("battery_modus","-1"))
      	);        
      String a=new LVConfigUpdate(xml_lci).toString();
      sendtoECM(a);
	}
    
    /**
     * Xml File will be sent to ECM.
     * @param message
     */
    private void sendtoECM(String message) {
    	
        // Check that we're actually connected before trying anything
        if (ECar.mBluetoothClient.getState() == BlueToothClient.STATE_CONNECTED) {
        	if(D)  Log.e(TAG,message);
        	// Check that there's actually something to send
            if (message.length() > 0) {
                // Get the message bytes and tell the BluetoothChatService to write
                byte[] send = message.getBytes();                
                ECar.mBluetoothClient.write(send);
            }                        
        }        
        else{        	
        	if(D) Log.e(TAG, "sendquery blocked not connected");            
        	Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();            
            return;
        }        
    } 
//****************************************Bluetooth setup in every activity********************************************
    
    @Override
    public boolean onPrepareOptionsMenu(Menu menu){
        MenuInflater inflater = getMenuInflater();
        menu.clear();
        if(ECar.mBluetoothClient.getState()==3)
        	inflater.inflate(R.menu.ecar_connected, menu);
        else
        	if(iD){
        		inflater.inflate(R.menu.ecar_connected, menu);	
        	}
        	else{
        		inflater.inflate(R.menu.option_menu, menu);
        	}
    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {        
        case R.id.scan:
            // Launch the DeviceListActivity to see devices and do scan
            Intent serverIntent = new Intent(this, DeviceListActivity.class);            
            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);            
            return true;        
        
        case R.id.discoverable:
            // Ensure this device is discoverable by others            
        	ensureDiscoverable();            
        	return true;
        
        case R.id.Trennen:        	
        	return true;        	
        
        case R.id.einreichen:
        	sendConfig(this);
        	return true;
        }        
        return false;    
    }
    
    private void ensureDiscoverable() {
        
    	if(D) Log.d(TAG, "ensure discoverable");        
        if (ECar.mBluetoothAdapter.getScanMode() !=            
        	BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {            
        	Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);            
        	discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);            
        	startActivity(discoverableIntent);       
        }    
    }

    private void setupBlueToothClient(){    	
        ECar.mBluetoothClient = new BlueToothClient(_Handler);        
    }
    
    @Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(D) Log.d(TAG, "onActivityResult " + resultCode);
        switch (requestCode) {
        case REQUEST_CONNECT_DEVICE:
            // When DeviceListActivity returns with a device to connect
            if (resultCode == Activity.RESULT_OK) {
                // Get the device MAC address
                String address = data.getExtras()
                                     .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                // Get the BLuetoothDevice object
                BluetoothDevice device = ECar.mBluetoothAdapter.getRemoteDevice(address);
                // Attempt to connect to the device
                ECar.mBluetoothClient.connect(device);
            }
            break;
        case REQUEST_ENABLE_BT:
            // When the request to enable Bluetooth returns
            if (resultCode == Activity.RESULT_OK) {
                // Bluetooth is now enabled, so set up a chat session
                setupBlueToothClient();
            } else {
                // User did not enable Bluetooth or an error occured
            	if(D) Log.d(TAG, "BT not enabled");
                Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }
    //***********************************************************************************************
}